package com._5704.website.controller;


import com._5704.website.entity.Activity;
import com._5704.website.entity.User;
import com._5704.website.exception.WebsiteException;
import com._5704.website.exception.WebsiteExceptionEnum;
import com._5704.website.form.ActivityForm;
import com._5704.website.service.ServiceImpl.ActivityServiceImpl;
import com._5704.website.service.ServiceImpl.UserServiceImpl;
import com._5704.website.util.JsonUtil;
import com._5704.website.util.JwtUtil;
import com._5704.website.vo.JsonVO;
import com._5704.website.vo.activityVO.ActivityVO;
import com._5704.website.vo.userVO.UserVO;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Yiyoung
 * @since 2021-07-25
 */
@RestController
@RequestMapping("/activity")
@Validated
@Log4j2
public class ActivityController {
    @Autowired
    private ActivityServiceImpl activityService;
    @Autowired
    private UserServiceImpl userService;
    /**
     * 展示一个活动
     * @param id 活动id
     * @param token token
     * @return
     */
    @RequiresRoles("insider")
    @GetMapping("/show")
    public JsonVO<Object> show(@RequestParam Integer id, @RequestHeader("token")String token){
        // 获得活动
        Activity activity = activityService.getActivity(id);
        // 检查活动是否可以被查看
        if (!activityService.isShow(activity,JwtUtil.getUserId(token))){
            throw new WebsiteException(WebsiteExceptionEnum.ACTIVITY_NOT_SHOW);
        }
        return JsonUtil.success(activity);
    }

    /**
     * 获得多个活动
     * @param page 页数
     * @param num 数量
     * @param type 活动类型
     *
     * @param token token
     * @return
     */

//    @RequiresRoles("insider")
    @GetMapping("/showMany")
    public JsonVO<Object> showMany(@Min(value = 0,message = "页数不能少于0") @RequestParam  int page,
                           @Min(value = 1,message = "数量不能少于1") @RequestParam  int num,
                           @RequestParam int type,
                           @RequestHeader(value = "token",required = false)String token){

        //  是否是所有人可查看
        boolean isGetAll  = false;
        String userId = "";
       if (token != null && !token.isEmpty()){
            userId = JwtUtil.getUserId(token);
           User user = userService.getUser(userId);
           isGetAll = userService.isInsider(user) || userService.isAdmin(user);
       }



        // 获得活动
        List<Activity> activityList = activityService.getActivities(page,num,type,isGetAll);

        // 获得可以查看的
        List<ActivityVO> activityVOList = new ArrayList<>();
        if (!userId.isEmpty()){
            String uid = userId;
            activityList = activityList.stream()
                    .filter(activity -> activityService.isShow(activity, uid)).collect(Collectors.toList());
        }

        activityList.forEach(e-> {
                    UserVO userVO = userService.getUserVO(userService.getUser(e.getUser()));
                    activityVOList.add(activityService.getActivityVO(e,userVO));
                });


        return JsonUtil.success(activityVOList);
    }


    /**
     * 发布活动
     * @param activityForm 活动表单
     * @param bindingResult 数据检查参数，必填
     * @param token token
     * @return
     */
    @RequiresRoles("admin")
    @PostMapping("/release")
    public JsonVO<String> release(@Valid @RequestBody ActivityForm activityForm,
                          BindingResult bindingResult,
                          @RequestHeader(value = "token")String token){
        // 活动时间早于展示时间
        if (activityForm.getActiveTime().before(activityForm.getShowTime())){
            throw new WebsiteException(WebsiteExceptionEnum.SHOW_TIME_illegal);
        }
        // 活动时间早于现在，设置为现在
        if (activityForm.getActiveTime().before(new Date())){
            activityForm.setActiveTime(new Date());
        }
        // 展示时间早于现在，设置为现在
        if (activityForm.getShowTime().before(new Date())){
            activityForm.setShowTime(new Date());
        }

       // 创建活动
        activityService.createActivity(activityForm, JwtUtil.getUserId(token));

        return JsonUtil.success();
    }

    @RequiresRoles("admin")
    @GetMapping("/delete")
    public JsonVO<String> delete(@RequestParam Integer id, @RequestHeader("token")String token){
        // 判断是否存在
        Activity activity = activityService.getActivity(id);
        // 删除
        activityService.delete(activity);

        return JsonUtil.success();
    }

    @RequiresRoles("admin")
    @PostMapping("/modify")
    public JsonVO<String> modify(@Valid @RequestBody ActivityForm activityForm, @RequestHeader("token")String token){
        Integer id = activityForm.getId();
        if (id == null){
            throw new WebsiteException(WebsiteExceptionEnum.DATA_ERROR,"id不能为空");
        }
        // 得到活动
        Activity activity = activityService.getActivity(id);
        // 设置更新信息
        activityService.setModifyData(activity, activityForm);
        // 更新活动
        activityService.updateActivity(activity);
        return JsonUtil.success();
    }

    /**
     * 获得总数
     * @return
     */
//    @RequiresRoles("insider")
    @GetMapping("/getNum")
    public JsonVO<Object> getNum(@RequestParam int type, @RequestHeader(value = "token",required = false)String token){
        boolean isGetAll  = false;
        // 获得是否是获得所有
        String userId = "";
        if (token != null && !token.isEmpty()){
            userId = JwtUtil.getUserId(token);
            User user = userService.getUser(userId);
            isGetAll = userService.isInsider(user) || userService.isAdmin(user);
        }
        // 获得数量
        int total = activityService.getNum(type,isGetAll);
        // 设置返回值
        Map<String,Integer> numMap = new HashMap<>();
        numMap.put("num",total);

        return JsonUtil.success(numMap);
    }

    /**
     * 获得总数
     * @return
     */
    @RequiresRoles("insider")
    @GetMapping("/getSearchNum")
    public JsonVO<Object> getSearchNum(@RequestParam String name, @RequestHeader("token")String token){
        int num = activityService.getNum(name);

        Map<String,Integer> numMap = new HashMap<>();

        numMap.put("num",num);

        return JsonUtil.success(numMap);
    }

    /**
     * 获得总数
     * @return
     */
    @RequiresRoles("insider")
    @GetMapping("/search")
    public JsonVO<Object> search(@RequestParam String name,
                                 @Min(value = 0,message = "页数不能少于0") @RequestParam  int page,
                                 @Min(value = 1,message = "数量不能少于1") @RequestParam  int num,
                                 @RequestHeader("token")String token){
        // 获取用户
        List<Activity> activityByName = activityService.getActivityByName(name, page, num);

        activityByName = activityByName.stream()
                .filter(activity -> activityService.isShow(activity,JwtUtil.getUserId(token)) )
                .collect(Collectors.toList());

        return JsonUtil.success(activityByName);


    }

    @RequiresRoles("admin")
    @PostMapping("/uploadPic")
    public JsonVO<Object> uploadPic(@RequestParam MultipartFile file){
        String picPath = activityService.uploadPic(file);

        return JsonUtil.success(picPath);
    }
}
